/*
 * File Name:               UIAlpha.cs
 *
 * Description:             继承于MonoBehaviour的类
 * Author:                  lisiyu <576603306@qq.com>

 * Create Date:             2017/04/10
 */

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

[ExecuteInEditMode]
public class UIAlpha : MonoBehaviour
{
    public enum Mode
    {
        Equal,
        Multi,
    }

    private struct AlphaData
    {
        private Graphic mGraphic;
        private float mOldValue;

        public AlphaData(Graphic graphic)
        {
            mGraphic = graphic;
            mOldValue = graphic.color.a;
        }

        public void multiValue(float value)
        {
            setValue(mOldValue * value);
        }

        public void setValue(float value)
        {
            if (mGraphic == null) return;

            var tmpColor = mGraphic.color;
            tmpColor.a = value;
            mGraphic.color = tmpColor;
        }

        public void resetValue()
        {
            setValue(mOldValue);
        }
    }

    [Range(0f, 1f)]
    public float Value = 1;
    public Mode mode = Mode.Multi;
    [HideInInspector]
    public UIAlpha parent;

    private float excutedValue = 1;
    private List<AlphaData> mDatas;

    private void Start()
    {
        var graphics = GetComponentsInChildren<Graphic>(false);
        if (graphics == null || graphics.Length == 0) return;
        mDatas = new List<AlphaData>();
        foreach (var gra in graphics)
        {
            mDatas.Add(new AlphaData(gra));
        }
    }

    private void LateUpdate()
    {
        if (parent != null)
            Value = parent.Value;

        if (excutedValue == Value)
            return;

        excutedValue = Value;
        if (mDatas == null || mDatas.Count == 0) return;
        if (mode == Mode.Equal)
        {
            foreach (var tmp in mDatas)
            {
                tmp.setValue(Value);
            }
        }
        else
        {
            foreach (var tmp in mDatas)
            {
                tmp.multiValue(Value);
            }
        }
    }

    private void OnDestroy()
    {
        if (mDatas == null || mDatas.Count == 0) return;
        foreach (var tmp in mDatas)
        {
            tmp.resetValue();
        }
    }

    public void ResetValue()
    {
        if (mDatas == null || mDatas.Count == 0) return;
        foreach (var tmp in mDatas)
        {
            tmp.resetValue();
        }
    }
}